package me.guowenlong.rxextension.ext;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.guowenlong.rxextension.CustomException;
import me.guowenlong.rxextension.bean.ResponseEntity;
import me.guowenlong.rxextension.ext.exception.MyException;
import me.guowenlong.rxextension.ext.exception.RetryException;
import me.guowenlong.transformer.bean.RetryBean;
import me.guowenlong.transformer.core.ExtendTransformer;
import me.guowenlong.rxextension.ext.exception.UnauthorizedException;
import retrofit2.Response;

/**
 * desc   : 生成Transformer的工具
 * author : guowenlong
 * Email  : guowenlong20000@gmail.com
 * time   : 2019年01月04日10 : 33
 */
public class TransformerUtils {
    private static final String TAG = "utils";

    public static <V, T extends Response<ResponseEntity<V>>> ExtendTransformer<T> handleGlobalError(Activity activity) {
        ExtendTransformer<T> transformer = new ExtendTransformer<>();
        transformer.setFlapMap(t -> {
            Log.e(TAG, "utils" + "code : " + t.code());
            switch (t.code()) {
                case 401:
                    return Observable.error(UnauthorizedException::new);
            }
            if (t.body() != null) {
                if (t.body().getCode() == 200) {
                    Toast.makeText(activity.getApplicationContext(), "业务码:" + t.body().getCode() + "业务失败!", Toast.LENGTH_LONG).show();
                    return Observable.error(FailException::new);
                }
            }
            return Observable.just(t);
        });
        transformer.setOnErrorResumeNext(throwable -> {
            // TODO: 2019/1/16 0016 一些系统自带的异常 比如网络异常 可以单独判断是否需要重试之类的操作
            if (throwable instanceof MyException) {
                return Observable.error(new Exception());
            } else {
                return Observable.error(throwable);
            }
        });
        transformer.setRetryWhen(throwable -> {
            if (throwable instanceof UnauthorizedException) {
                // TODO: 2019/1/8 登录authorize异常 (过期或错误) 去刷新
                Toast.makeText(activity.getApplicationContext(), "UnauthorizedException!", Toast.LENGTH_LONG).show();
            }
            if (throwable instanceof RetryException) {
                Single<Boolean> single = Single
                        .create((SingleOnSubscribe<Boolean>) emitter -> {
                            // TODO: 2019/1/8 可以写一些逻辑
                            emitter.onSuccess(true);
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(Schedulers.io());
                return RetryBean.getOneTimeRetryBean(single);
            } else {
                Log.e(TAG, "不重试");
                return RetryBean.getNilRetryBean();
            }
        });
        transformer.setOnErrorConsumer(throwable -> {
            // TODO: 2019/1/9 全局异常
            Log.e(TAG, "全局异常" + throwable.toString());
        });
        return transformer;
    }

    public static <T extends Response<ResponseEntity<?>>> ExtendTransformer<T> handleGlobalError1(Activity activity) {
        ExtendTransformer<T> transformer = new ExtendTransformer<>();
        transformer.setFlapMap(t -> {
            Log.e(TAG, "utils" + "code : " + t.code());
            switch (t.code()) {
                case 401:
                    return Observable.error(UnauthorizedException::new);
                default:
                    return Observable.just(t);
            }
        });
        transformer.setOnErrorResumeNext(throwable -> {
            if (throwable instanceof CustomException) {
                return Observable.error(new Exception());
            } else {
                return Observable.error(throwable);
            }
        });
        transformer.setRetryWhen(throwable -> {
            if (throwable instanceof UnauthorizedException) {
                // TODO: 2019/1/8 登录authorize异常 (过期或错误) 去刷新
                Toast.makeText(activity.getApplicationContext(), "UnauthorizedException!", Toast.LENGTH_LONG).show();
            }
            if (throwable instanceof RetryException) {
                Single<Boolean> single = Single
                        .create((SingleOnSubscribe<Boolean>) emitter -> {
                            // TODO: 2019/1/8 可以写一些逻辑
                            emitter.onSuccess(true);
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(Schedulers.io());
                return RetryBean.getOneTimeRetryBean(single);
            } else {
                Log.e(TAG, "不重试");
                return RetryBean.getNilRetryBean();
            }
        });
        transformer.setOnErrorConsumer(throwable -> {
            // TODO: 2019/1/9 全局异常
            Log.e(TAG, "全局异常" + throwable.toString());
        });
        return transformer;
    }
}